package project.dade.cn.bst.base;

import java.util.ArrayList;

import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public class PageManager {
	private IPage iPage;
	private FragmentActivity mActivity;
	private FragmentManager manager;
	private ArrayList<ParentFragment> fragments;
	private int currIndex = -1;

	public PageManager(FragmentActivity activity, IPage iPage) {
		this.mActivity = activity;
		this.iPage = iPage;
		this.fragments = new ArrayList<ParentFragment>();
		init(iPage.getHolderID());
	}

	public void init(int holderID) {
		manager = mActivity.getSupportFragmentManager();
		iPage.putFragments(fragments);
		FragmentTransaction transaction = manager.beginTransaction();
		currIndex = iPage.getDefaultIndex();
		ParentFragment fragment = fragments.get(iPage.getDefaultIndex());
		transaction.add(holderID, fragment);
		transaction.commit();
	}

	public void switchPage(int index) {
		manager = mActivity.getSupportFragmentManager();
		FragmentTransaction transaction = manager.beginTransaction();
		currIndex=index;
		getCurrFragment().onPause();

		ParentFragment fragment = fragments.get(index);

		if (!fragment.isAdded()) {
			transaction.add(iPage.getHolderID(), fragment);
		} else {
			fragment.onResume();			
		}

		transaction.commit();
		operatePage(index);
	}

	private void operatePage(int index) {

		for (int i = 0; i < fragments.size(); i++) {
			ParentFragment fragment = fragments.get(i);
			FragmentTransaction ft = mActivity.getSupportFragmentManager()
					.beginTransaction();

			if (index == i) {
				ft.show(fragment);
			} else {
				ft.hide(fragment);
			}
			ft.commit();
		}
	}

	private ParentFragment getCurrFragment() {
		return fragments.get(currIndex);
	}
}
